package com.entertainment.ticketing.scheduling;

import com.entertainment.ticketing.entity.OrderInfo;
import com.entertainment.ticketing.repository.OrderInfoRepository;
import com.entertainment.ticketing.service.OrderService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
public class OrderAutoCancelScheduler {

    private final OrderInfoRepository orderRepo;
    private final OrderService orderService;

    public OrderAutoCancelScheduler(OrderInfoRepository orderRepo, OrderService orderService) {
        this.orderRepo = orderRepo;
        this.orderService = orderService;
    }

    // 每分钟检查一次，取消超过10分钟未支付的订单
    @Scheduled(fixedDelay = 60000)
    public void cancelExpiredPendingOrders() {
        LocalDateTime cutoff = LocalDateTime.now().minusMinutes(10);
        List<OrderInfo> expired = orderRepo.findByStatusAndCreatedAtBefore((byte)1, cutoff);
        for (OrderInfo o : expired) {
            try {
                orderService.cancelOrder(o.getOrderNo());
            } catch (Exception ignored) {
                // 避免影响后续任务
            }
        }
    }
}